import 'package:core/core.dart';

/// 基础的加载model类
abstract class ViewStateLoadModel<T> extends ViewStateModel {
  /// 第一个进入页面调用
  Future initData() async {
    if (!cached) {
      setBusy();
    }

    try {
      bool isEmpty = await loadData();
      if (isEmpty)
        setEmpty();
      else
        setIdle();
    } catch (e, s) {
      //页面不为空不处理状态
      if (!pageEmpty()) {
        printErrorStack(e, s);
        return;
      }

      setError(e, s);
      onError(e, s);
    }
  }

  bool pageEmpty() => true;

  /**
   * 加载数据
   * 返回 是否是空数据
   */
  Future<bool> loadData();

  onError(e, s) {}
}

/// 基础的加载和处理缓存的model类
abstract class ViewStateLoadCacheModel<T> extends ViewStateLoadModel
    with CacheData {
  /**
   * 初始化缓存数据
   * 返回 是否有缓存数据
   */
  bool initCacheData() {
    try {
      Map? cacheData = getCacheData();
      if (cacheData != null && cacheData.isNotEmpty) {
        setCached();
        handleCacheData(cacheData);
        return true;
      }
    } catch (e) {
      deleteCacheData();
      return false;
    }
    return false;
  }

  // 处理缓存数据
  void handleCacheData(Map cacheData);
}

/// 基础带R刷新的加载和处理缓存的model类
abstract class ViewStateRefreshLoadCacheModel<T>
    extends ViewStateLoadCacheModel {
  RefreshController refreshController = RefreshController();

  @override
  Future initData() async {
    if (!cached) {
      setBusy();
    }
    await refresh();
  }

  //下拉刷新
  Future refresh() async {
    try {
      bool isEmpty = await loadData();
      refreshController.refreshCompleted(resetFooterState: true);
      if (isEmpty)
        setEmpty();
      else
        setIdle();
    } catch (e, s) {
      refreshController.refreshFailed();
      //页面不为空不处理状态
      if (!pageEmpty()) {
        printErrorStack(e, s);
        return;
      }
      setError(e, s);
      onError(e, s);
    }
  }

  @override
  void dispose() {
    refreshController.dispose();
    super.dispose();
  }
}
